package main

import (
	"context"
	"gitee.com/bei_yi_ning/gorder/common/broker"
	"gitee.com/bei_yi_ning/gorder/common/client"
	"gitee.com/bei_yi_ning/gorder/common/discovery"
	"gitee.com/bei_yi_ning/gorder/common/logging"

	"gitee.com/bei_yi_ning/gorder/common/tracing"
	"gitee.com/bei_yi_ning/gorder/kitchen/adapters"
	"gitee.com/bei_yi_ning/gorder/kitchen/infra/consumer"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"os"
	"os/signal"
	"syscall"
)

func init() {
	logging.Init()
}

func main() {
	serviceName := viper.GetString("kitchen.service-name")

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// 实例化opentelemetry
	shutdown, err := tracing.InitJaegerProvider(viper.GetString("jaeger.url"), serviceName)
	if err != nil {
		logrus.Fatal(err)
	}
	defer shutdown(ctx)
	//

	// 注册到consul  查看存活
	deregisterFunc, err := discovery.RegisterToConsul(ctx, serviceName)
	if err != nil {
		logrus.Fatal(err)
	}
	defer func() {
		_ = deregisterFunc()
	}()
	// 注册完毕

	orderClient, close, err := client.NewOrderGRPCClient(ctx)
	if err != nil {
		logrus.Fatal(err)
	}
	defer close()

	// mq
	ch, closeCh := broker.Connect(
		viper.GetString("rabbitmq.user"),
		viper.GetString("rabbitmq.password"),
		viper.GetString("rabbitmq.host"),
		viper.GetString("rabbitmq.port"),
	)
	defer func() {
		_ = ch.Close()
		_ = closeCh()
	}()

	orderGRPC := adapters.NewOrderGRPC(orderClient)
	// 先获取orderclient 该结构体实现了updateorder 然后被ordergrpc持有
	// ordergrpc实现了orderservice接口即实现updateorder方法  其真实的调用还是orderclient的实现 只是封装了一层
	// ordergrpc再被consumer持有 consumer只依赖一个interface 就是orderservice接口
	go consumer.NewConsumer(orderGRPC).Listen(ch)

	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		_ = <-sigs
		logrus.Infof("received shutdown signal")
		os.Exit(0)
	}()

	logrus.Println("press ctrl-c to exit")
	select {}
}
